package cerebrum.controller.wallpaper;

import cerebrum.common.EmptyChecker;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtil {
    private static Logger log = LoggerFactory.getLogger(HttpUtil.class);

    private HttpUtil() {

    }

    /**
     * 下载图片
     *
     * @param address  url
     * @param dir      文件保存路径
     * @param name     文件名称
     * @param isFirst  是否需重定向
     */
    public static void imgGet(String address, String dir, String name, boolean isFirst) {
        new Thread(() -> {
            try {
                CloseableHttpClient hc = HttpClients.createDefault();

                HttpGet get = new HttpGet(address);
                var hr = hc.execute(get);
                log.info("{} 连接图片服务器成功",address);
                HttpEntity entity = hr.getEntity();
                InputStream in = entity.getContent();
                byte[] bytes = new byte[1024];
                File file = new File(dir + File.separator + name);
                file.createNewFile();

                try (FileOutputStream fos = new FileOutputStream(file);) {
                    int i = 0;
                    while ((i = in.read(bytes)) != -1) {
                        fos.write(bytes, 0, i);
                    }
                }
                log.info("{} 下载成功,文件名: {}",address,name);
            } catch (Exception e) {
                if (!isFirst) {
                    log.error("{} 下载失败",address);
                    return;
                }else {
                    String stackTrace = getStackTrace(e);
                    int start = stackTrace.indexOf("URI:") + 5;
                    int end = stackTrace.indexOf(".jpg");
                    int in = (end == -1 ? stackTrace.indexOf(".jpeg") + 5 : end + 4);
                    String url = "https:" + stackTrace.substring(start, in);
                    url.replaceAll(" ", "%20");
                    log.error("{} 下载失败,开始尝试重定向： {}",address,dir);
                    imgGet(url, dir, name, false);
                }
            }
        }).start();
    }

    public static String getStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        try {
            throwable.printStackTrace(pw);
            return sw.toString();
        } finally {
            pw.close();
        }
    }

    /**
     * 发送HttpGet请求
     *
     * @param url
     * @return
     */
    public static String doGet(String url, Map<String, String> header) {
        //1.获得一个httpclient对象
        try (CloseableHttpClient httpclient = HttpClients.createDefault();) {
            //2.生成一个get请求
            HttpGet get = new HttpGet(url);
            if (EmptyChecker.notEmpty(header)) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    get.setHeader(entry.getKey(), entry.getValue());
                }
            }
            //3.执行get请求并返回结果
            CloseableHttpResponse response = httpclient.execute(get);
            //4.处理结果，这里将结果返回为字符串
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 发送HttpPost请求，参数为map
     *
     * @param url
     * @param map
     * @return
     */
    public static String doPost(String url, Map<String, Object> map) {
        try (CloseableHttpClient httpclient = HttpClients.createDefault();) {
            List<NameValuePair> formparams = new ArrayList<>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                //给参数赋值
                formparams.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(entity);
            CloseableHttpResponse response = httpclient.execute(httppost);

            HttpEntity entity1 = response.getEntity();
            return EntityUtils.toString(entity1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
